package org.simple.jdbc.resolver;

import org.simple.jdbc.statement.annotation.Delete;
import org.simple.jdbc.statement.bean.DeleteBean;
import org.simple.jdbc.statement.bean.Expression;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jinchengzhen
 */
public class DeleteResolver extends StatementResolver {
    private DeleteBean deleteBean;

    public DeleteResolver(Class<?> tableClazz, Method method, Object[] args) {
        super(tableClazz, method, args);
    }

    @Override
    public DeleteBean resolver() {
        if (method.isAnnotationPresent(Delete.class)) {
            Annotation[][] annotationArr = method.getParameterAnnotations();
            List<Expression> expressionList = new ArrayList<>();
            if (deleteBean == null) {
                deleteBean = new DeleteBean();
                tableBean = getTableBean();
                deleteBean.setTableBean(tableBean);
            }
            boolean noExp = true;
            if (annotationArr != null) {
                int i = 0;
                for (Annotation[] annotations : annotationArr) {
                    org.simple.jdbc.statement.annotation.Expression expressionAnnotation = getAnnotation(annotations, org.simple.jdbc.statement.annotation.Expression.class);
                    if (expressionAnnotation != null) {
                        Object paramVal = args[i];
                        Expression expression = getExpression(expressionAnnotation, paramVal, tableBean);
                        expressionList.add(expression);
                        noExp = false;
                    }
                    i++;
                }
            }
            if (noExp && args != null && args.length > 0 && tableBean.getPrimaryColumn() != null) {
                Expression expression = addPrimaryExpression();
                expression.setColumn(getFiledValue(args[0], tableBean.getPrimaryColumn().getColumnName(), tableBean));
                expressionList.add(expression);
            }

            deleteBean.setExpressionList(expressionList);
            return deleteBean;
        }
        return null;
    }
}
